package com.eshop.we.common;

import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Set;

public class ParameterRequestWrapper extends HttpServletRequestWrapper implements ParameterRequest{

	private ParameterRequestExecuter  parameter = new ParameterRequestExecuter();
	
	private byte[] requestBody = null;   
	 
	@SuppressWarnings({ "unchecked" })
	public ParameterRequestWrapper(HttpServletRequest request,Set<String> urls) {
		// 将request交给父类，以便于调用对应方法的时候，将其输出，其实父亲类的实现方式和第一种new的方式类似
		super(request);
		//缓存请求body  
        try {  
            requestBody = StreamUtils.copyToByteArray(request.getInputStream());  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
		// 将参数表，赋予给当前的Map以便于持有request中的参数
		parameter.getParams().putAll(request.getParameterMap());
		parameter.modifyParameterValues(request.getServletPath().trim(),urls);
	}
	
	@Override
	public String getParameter(String name) {// 重写getParameter，代表参数从当前类中的map获取
		return parameter.getParameter(name);
	}
	
	@Override
	public String[] getParameterValues(String name) {// 同上
		return parameter.getParameterValues(name);
	}

	@Override
	public void addAllParameters(Map<String, Object> otherParams) {// 增加多个参数
		parameter.addAllParameters(otherParams);
	}

	@Override
	public void addParameter(String name, Object value) {// 增加参数
		parameter.addParameter(name, value);
	}
	
	/** 
     * 重写 getInputStream() 
     */  
    @Override  
    public ServletInputStream getInputStream() throws IOException {  
        if(requestBody == null){  
            requestBody= new byte[0];  
        }  
        final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);    
        return new ServletInputStream() {
			@Override
			public boolean isFinished() {
				return false;
			}

			@Override
			public boolean isReady() {
				return false;
			}

			@Override
			public void setReadListener(ReadListener readListener) {

			}

			@Override
            public int read() throws IOException {    
                return bais.read();    
            }    
        };    
    }  
  
    /** 
     * 重写 getReader() 
     */  
    @Override  
    public BufferedReader getReader() throws IOException {  
        return new BufferedReader(new InputStreamReader(getInputStream()));    
    }

	public byte[] getRequestBody() {
		return requestBody;
	}

	public void setRequestBody(byte[] requestBody) {
		this.requestBody = requestBody;
	}  
    

}